﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;

namespace BitPortal.Admin.Module.BaseModule
{
    public partial class BaseModuleAddEdit : Controls.BaseAdminPage
    {
        protected override void OnInit(EventArgs e)
        {
            PermissionBLL.CheckRoleThrowException(role: "PageView", useExceptionHandler: true);
            PermissionBLL.CheckRoleThrowException(role: "PageEdit", useExceptionHandler: true);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!IsPostBack)
            {
                BindData(Request.QueryString["BaseModuleID"].ToInt32TryParse());
            }
        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageEdit");
                int id = Utils.GeneralUtils.ToInt32TryParse(txtID.Text);
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                ModuleBase mb = bitEnt.ModuleBases.SingleOrDefault(ent => ent.ModuleBaseID == id);
                if (mb != null)
                {
                    mb.Name = txtName.Text;
                    mb.Description = txtDescription.Text;

                    foreach (BaseModuleConfig config in GetBaseModuleConfig())
                    {
                        BaseModuleConfig c = mb.BaseModuleConfigs.SingleOrDefault(ent => ent.Name == config.Name);
                        if (c != null)
                        {
                            c.DataType = config.DataType;
                            c.Value = config.Value;
                            c.AllowUserConfig = config.AllowUserConfig;
                        }
                        else
                        {
                            mb.BaseModuleConfigs.Add(config);
                        }
                    }
                    if (bitEnt.SaveChanges() > 0)
                    {
                        ShowNotification("Sửa sản phẩm thành công!");
                        ResourceManager1.AddScript("parent.Ext.WindowMgr.getActive().hide();parent.Ext.getCmp('" + Request.QueryString["ReloadID"] + "').getStore().reload();");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }

        }

        protected void btnSetup_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageEdit");
                foreach (SelectedRow row in ImageView.SelectedRows)
                {
                    try
                    {
                        ModuleBase mb = ModuleBLL.ReadBaseModuleConfig("~" + row.RecordID);
                        if (mb.Insert() > 0)
                        {
                            ShowNotification("Thêm module thành công!");
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                }
                ResourceManager1.AddScript("parent.Ext.WindowMgr.getActive().hide();parent.Ext.getCmp('" + Request.QueryString["ReloadID"] + "').getStore().reload();");
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected List<BaseModuleConfig> GetBaseModuleConfig()
        {
            List<Models.BaseModuleConfig> listPropertyValues = new List<Models.BaseModuleConfig>();
            foreach (var c in Panel5.ContentControls)
            {
                switch (c.GetType().Name)
                {
                    case "Checkbox":
                        Ext.Net.Checkbox ck = (Ext.Net.Checkbox)c;
                        Models.BaseModuleConfig property = new Models.BaseModuleConfig()
                        {
                            ConfigID = Utils.GeneralUtils.ToInt32TryParse(ck.ID.Substring(8)),
                            Value = ck.Checked.ToString(),
                            AllowUserConfig = ck.Enabled,
                            DataType = "Boolean",
                            Name = ck.Name
                        };
                        listPropertyValues.Add(property);
                        break;
                    case "TextField":
                        Ext.Net.TextField tf = (Ext.Net.TextField)c;
                        Models.BaseModuleConfig property2 = new Models.BaseModuleConfig()
                        {
                            ConfigID = Utils.GeneralUtils.ToInt32TryParse(tf.ID.Substring(8)),
                            Value = tf.Text,
                            AllowUserConfig = tf.Enabled,
                            DataType = "String",
                            Name = tf.Name,
                        };
                        listPropertyValues.Add(property2);
                        break;
                    case "HtmlEditor":
                        Ext.Net.HtmlEditor ed = (Ext.Net.HtmlEditor)c;
                        Models.BaseModuleConfig property3 = new Models.BaseModuleConfig()
                        {
                            ConfigID = Utils.GeneralUtils.ToInt32TryParse(ed.ID.Substring(8)),
                            Value = ed.Text,
                            AllowUserConfig = ed.Enabled,
                            DataType = "Text",
                            Name = ed.Name
                        };
                        listPropertyValues.Add(property3);
                        break;
                    case "NumberField":
                        Ext.Net.NumberField nf = (Ext.Net.NumberField)c;
                        Models.BaseModuleConfig property4 = new Models.BaseModuleConfig()
                        {
                            ConfigID = Utils.GeneralUtils.ToInt32TryParse(nf.ID.Substring(8)),
                            Value = nf.Text,
                            AllowUserConfig = nf.Enabled,
                            DataType = (nf.AllowDecimals) ? "Double" : "Interger",
                            Name = nf.Name
                        };
                        listPropertyValues.Add(property4);
                        break;
                }
            }
            return listPropertyValues;
        }

        protected void LoadBaseModuleConfig(ModuleBase mb)
        {
            Panel5.ContentControls.Clear();
            List<BaseModuleConfig> configs = ModuleBLL.ReadBaseModuleConfig(mb.Path).BaseModuleConfigs.ToList();
            foreach (Models.BaseModuleConfig property in configs)
            {
                BaseModuleConfig config = mb.BaseModuleConfigs.SingleOrDefault(ent => ent.Name == property.Name);
                if (config != null)
                {
                    property.ConfigID = config.ConfigID;
                    property.Value = config.Value;
                }
                switch (property.DataType)
                {
                    case "Boolean":
                        Ext.Net.Checkbox control = new Ext.Net.Checkbox() { };
                        control.ID = "property" + property.ConfigID;
                        control.Checked = property.Value.Equals("True") ? true : false;
                        control.FieldLabel = property.Name;
                        control.Enabled = property.AllowUserConfig;
                        control.Name = property.Name;
                        Panel5.ContentControls.Add(control);
                        break;
                    case "String":
                        Ext.Net.TextField control1 = new Ext.Net.TextField() { Width = new Unit(400) };
                        control1.ID = "property" + property.ConfigID;
                        control1.Text = property.Value;
                        control1.FieldLabel = property.Name;
                        control1.Enabled = property.AllowUserConfig;
                        control1.Name = property.Name;
                        Panel5.ContentControls.Add(control1);
                        break;
                    case "Text":
                        Ext.Net.HtmlEditor control2 = new Ext.Net.HtmlEditor() { };
                        control2.ID = "property" + property.ConfigID;
                        control2.Text = property.Value;
                        control2.FieldLabel = property.Name;
                        control2.Enabled = property.AllowUserConfig;
                        control2.Name = property.Name;
                        Panel5.ContentControls.Add(control2);
                        break;
                    case "Interger":
                        Ext.Net.NumberField control3 = new Ext.Net.NumberField() { };
                        control3.MinValue = 0;
                        control3.AllowDecimals = false;
                        control3.ID = "property" + property.ConfigID;
                        control3.Text = property.Value;
                        control3.FieldLabel = property.Name;
                        control3.Enabled = property.AllowUserConfig;
                        control3.Name = property.Name;
                        Panel5.ContentControls.Add(control3);
                        break;
                    case "Double":
                        Ext.Net.NumberField control4 = new Ext.Net.NumberField() { };
                        control4.MinValue = 0;
                        control4.ID = "property" + property.ConfigID;
                        control4.Text = property.Value;
                        control4.FieldLabel = property.Name;
                        control4.Enabled = property.AllowUserConfig;
                        control4.Name = property.Name;
                        Panel5.ContentControls.Add(control4);
                        break;
                    case "Datetime":
                        Ext.Net.DateField control5 = new Ext.Net.DateField() { };
                        control5.ID = "property" + property.ConfigID;
                        control5.SelectedDate = Convert.ToDateTime(property.Value);
                        control5.FieldLabel = property.Name;
                        control5.Enabled = property.AllowUserConfig;
                        control5.Name = property.Name;
                        Panel5.ContentControls.Add(control5);
                        break;
                }
            }
        }

        public void BindData(int moduleId = 0)
        {
            if (moduleId == 0)
            {
                txtID.Text = "0";
                Store1.DataSource = ModuleBLL.GetListSourceModules();
                Store1.DataBind();
                Panel1.Show();
                Panel2.Hide();
                return;
            }
            else
            {
                ModuleBase mb = ModuleBLL.GetBaseModuleByID(moduleId);
                if (mb != null)
                {
                    txtID.Text = moduleId.ToString();
                    txtName.Text = mb.Name;
                    txtDescription.Text = mb.Description;

                    LoadBaseModuleConfig(mb);

                    Panel1.Hide();
                    Panel2.Show();
                }
            }
        }
    }
}